import psutil
import ctypes
from ctypes import wintypes

# Windows API constants and functions
TH32CS_SNAPMODULE = 0x00000008
TH32CS_SNAPMODULE32 = 0x00000010

CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot
Module32First = ctypes.windll.kernel32.Module32First
Module32Next = ctypes.windll.kernel32.Module32Next
CloseHandle = ctypes.windll.kernel32.CloseHandle

class MODULEENTRY32(ctypes.Structure):
    _fields_ = [
        ("dwSize", wintypes.DWORD),
        ("th32ModuleID", wintypes.DWORD),
        ("th32ProcessID", wintypes.DWORD),
        ("GlblcntUsage", wintypes.DWORD),
        ("ProccntUsage", wintypes.DWORD),
        ("modBaseAddr", ctypes.POINTER(ctypes.c_byte)),
        ("modBaseSize", wintypes.DWORD),
        ("hModule", wintypes.HMODULE),
        ("szModule", ctypes.c_char * 256),
        ("szExePath", ctypes.c_char * 260)
    ]

def find_pid_by_name(process_name):
    for proc in psutil.process_iter(['pid', 'name']):
        if proc.info['name'] == process_name:
            return proc.info['pid']
    return None

def get_module_base_address(pid, module_name):
    hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid)
    if hSnapshot == wintypes.HANDLE(-1):
        return None

    me32 = MODULEENTRY32()
    me32.dwSize = ctypes.sizeof(MODULEENTRY32)

    if not Module32First(hSnapshot, ctypes.byref(me32)):
        CloseHandle(hSnapshot)
        return None

    while True:
        if me32.szModule.decode('utf-8') == module_name:
            CloseHandle(hSnapshot)
            return ctypes.addressof(me32.modBaseAddr.contents)

        if not Module32Next(hSnapshot, ctypes.byref(me32)):
            break

    CloseHandle(hSnapshot)
    return None

def check_game_status():
    process_name = "PlantsVsZombiesRH.exe"
    module_name = "UnityPlayer.dll"
    pid = find_pid_by_name(process_name)
    if pid:
        base_address = get_module_base_address(pid, module_name)
        return base_address is not None
    return False
